<script setup>
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
const userId = ref("");
onMounted(() => {
  userId.value = localStorage.getItem("userId");
});

const form = ref({
  password: "",
  password1: "",
});

// 表单验证规则
const rules = ref({
  password: [
    {
      required: true,
      message: "请输入新密码",
      trigger: "blur",
    },
    {
      min: 6,
      max: 20,
      message: "密码长度必须为6到20位",
      trigger: "blur",
    },
  ],
  password1: [
    {
      required: true,
      message: "请再次输入新密码",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (value != form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

// 表单引用
const passwordForm = ref(null);

// 提交表单
const submitForm = () => {
  passwordForm.value.validate(async (valid) => {
    if (valid) {
      await axios.patch(`http://localhost:3000/userList/${userId.value}`, {
        password: form.value.password,
      });
      ElMessage.success("修改成功");
    } else {
      ElMessage.error("请完善信息");
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  passwordForm.value.resetFields();
};
</script>

<template>
  <div>
    <userTitle>密码修改</userTitle>
    <br />
    <el-form ref="passwordForm" :model="form" :rules="rules" label-width="100px">
      <!-- 新密码 -->
      <el-form-item label="新密码" prop="password">
        <el-input
          style="width: 300px"
          v-model="form.password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item label="确认密码" prop="password1">
        <el-input
          style="width: 300px"
          v-model="form.password1"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <div class="changeBtn" @click="submitForm">修改</div>
        <div class="resBtn" @click="resetForm">重置</div>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.changeBtn,
.resBtn {
  margin: 10px;
  width: 100px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}
.changeBtn {
  background-color: #b895a7;
}
.changeBtn:hover {
  background-color: #b87b9a;
}
.resBtn {
  background-color: #b8b8b8;
}
.resBtn:hover {
  background-color: #b6a9a9;
}
</style>
